package com.sycu.socket.unit07;
import java.io.BufferedInputStream;  
import java.io.FileInputStream;  
import java.io.IOException;  
import java.net.DatagramPacket;  
import java.net.DatagramSocket;  
import java.net.InetAddress;  
  
public class UDPSender {  
    public static void main(String[] args) {  
        DatagramSocket sender = null;  
        InetAddress serverAddress = null;  
        BufferedInputStream bis = null;  
  
        try {  
            final int DEFAULT_PORT = 10086;  
            final String SOURCE_PATH = "D:\\a\\3.html";  
  
            // 创建UDP套接字  
            sender = new DatagramSocket();  
  
            // 指定服务器地址和端口  
            serverAddress = InetAddress.getByName("127.0.0.1");  
  
            // 读取文件数据  
            bis = new BufferedInputStream(new FileInputStream(SOURCE_PATH));  
            byte[] buffer = new byte[1024];  
            int bytesRead;  
  
            while ((bytesRead = bis.read(buffer)) != -1) {  
                // 创建数据报  
                DatagramPacket packet = new DatagramPacket(buffer, bytesRead, serverAddress, DEFAULT_PORT);  
  
                // 发送数据报  
                sender.send(packet);  
            }  
  
            // 发送空数据包作为文件结束信号  
            byte[] emptyData = new byte[0];  
            DatagramPacket endPacket = new DatagramPacket(emptyData, emptyData.length, serverAddress, DEFAULT_PORT);  
            sender.send(endPacket);  
  
            System.out.println("文件已发送完毕。");  
  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                if (bis != null) bis.close();  
                if (sender != null) sender.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
}